
import controlSchema from '../../model/controlList.js'
import {errorResult} from '../../utils/pubilc.js'


export default app => {

  /**
   * @description 查询
   * */
  app.get('/wpApi/getControlList', async (req, res) => {
    const {page, pageSize, name,} = req.query
    let result = {
      code: 0,
      msg: '数据异常',
      result: null
    }
    if(!page || !pageSize) {
      result = errorResult()
    }
    const skip = (page - 1 ) * pageSize
    let filter = {}
    if(name.trim()) {
      filter = {
        name: {
          $regex: name
        }
      }
    }
    const field = {_id: 0, __v: 0, _createTime: 0, _updateTime: 0}
    const count = await controlSchema.find(filter).count()
    const data = await controlSchema.find(filter, field ).skip(skip).limit(pageSize).sort({createTime: -1})
    result = {
      code: 0,
      msg: 'success',
      result: data,
      count
    }
    res.send(result)
  })

  /**
   * @description 新增
   * */
  app.post('/wpApi/saveControl', async (req, res) => {
    const { name, configInfo, remarks } = req.body;

    if (!configInfo.length || !name) {
      res.send(errorResult());
      return;
    }

    const updateData = {
      name,
      configInfo,
      remarks
    };

    if (req.body?.id) {
      // 更新操作
      try {
        // 使用$set操作符来明确指定替换configInfo字段
        await controlSchema.updateOne(
            { id: req.body.id },
            { $set: updateData }
        );
        res.send({ code: 0, msg: '操作成功' });
      } catch (e) {
        res.send({ code: 1, msg: '系统错误：' + e });
      }
    } else {
      // 新增操作保持不变
      controlSchema.create(updateData)
          .then(() => {
            res.send({ code: 0, msg: '操作成功' });
          })
          .catch((e) => {
            res.send({ code: 1, msg: '系统错误：' + e });
          });
    }
  });

  /**
   * @description 删除
   * */
  app.post('/wpApi/deleteControl', async (req, res) => {

    const {id} = req.body
    if(!id) {
      res.send(errorResult())
      return
    }
    controlSchema.deleteOne({
      id
    }).then(() => {
      res.send({
        code: 0,
        msg: '操作成功'
      })
    }).catch((e) => {
      res.send({
        code: 1,
        msg: '系统错误：' + e
      })
    })
  })

}
